﻿using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace Common.Swagger.Filter
{
    /// <summary>
    /// 敏感数据处理（响应）
    /// </summary>
    public class SensitiveDataSchemaFilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            if (context.MemberInfo == null)
            {
                return;
            }
            var attributes = context.MemberInfo.GetCustomAttributes(true).Select(s => s.GetType().Name);
            var excludeAttributes = attributes.Where(s => s == "SensitiveDataAttribute").Any();
            if (!excludeAttributes)
            {
                return;
            }
            schema.Description = "【脱敏数据】" + schema.Description;
            if (schema.Type == "array")
            {
                //由于Swagger的Example在小数点类型中显示的都是0，导致前端无法区分是整数还是小数
                schema.Items.Type = "string";
                //schema.Items.Format = "string";
                schema.Items.Example = OpenApiAnyFactory.CreateFor(schema.Items, "ZYS_****");
                return;
            }
            schema.Type = "string";
        }
    }
}
